package com.clw.controller;

import com.clw.dataobject.User;
import com.clw.enums.ResultEnum;
import com.clw.exception.SellException;
import com.clw.form.RegisterForm;
import com.clw.service.UserService;
import com.clw.utils.MD5SaltUtils;
import com.clw.utils.ResultVOUtils;
import com.clw.utils.StringUtils;
import com.clw.utils.VerificationCodeUtils;
import com.clw.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.Map;

/**
 * Created by Administrator on 2017-12-29.
 */
@Controller
@RequestMapping("/")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public ModelAndView login(){
        return new ModelAndView("login/login");
    }

    @ResponseBody
    @RequestMapping(value="/login/getCode")
    public void getCode(HttpServletResponse response, HttpSession session) throws IOException {
        ByteArrayInputStream bais;
        VerificationCodeUtils code;
        String strCode;
        code = new VerificationCodeUtils();
        bais = code.createImage();
        strCode = code.strCode;
        response.setContentType("image/jpeg");
        InputStream in=bais;
        int len;
        byte[] buf=new byte[1024];
        while((len =in.read(buf,0,1024))!=-1){
            response.getOutputStream().write(buf,0,len);
        }
        session.setAttribute("randomCode", strCode);
        response.getOutputStream().close();
    }

    @PostMapping("/login/doLogin")
    @ResponseBody
    public ResultVO doLogin(@RequestParam(value = "name", defaultValue = "") String name,
                            @RequestParam(value = "password", defaultValue = "") String password,
                            @RequestParam(value = "checCodeInput", defaultValue = "") String checCodeInput,
                            HttpServletResponse response,
                            Map<String, Object> map, HttpSession session) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String code=(String) session.getAttribute("randomCode");
        if (StringUtils.isEmpty(code)){
            return ResultVOUtils.error(ResultEnum.VERIFICATION_CODE_EXPIRED.getCode(),
                    ResultEnum.VERIFICATION_CODE_EXPIRED.getMessage());
        }
        if (code.toLowerCase().equals(checCodeInput.toLowerCase())){
            User user=userService.findByUserName(name);
            if (user==null){
                return ResultVOUtils.error(ResultEnum.LOGIN_FAIL.getCode(),
                        ResultEnum.LOGIN_FAIL.getMessage());
            }
            if (user.getStatus()==0){
                return ResultVOUtils.error(ResultEnum.LOGIN_FAIL_BY_STATUS.getCode(),
                        ResultEnum.LOGIN_FAIL_BY_STATUS.getMessage());
            }
            if (MD5SaltUtils.validPassword(password,user.getPassword())){
                session.setAttribute("user_id",user.getId());
                session.setAttribute("user_name",user.getUserName());
                return ResultVOUtils.success();
            }
            else {
                return ResultVOUtils.error(ResultEnum.LOGIN_FAIL.getCode(),
                        ResultEnum.LOGIN_FAIL.getMessage());
            }
        }
        else {
            return ResultVOUtils.error(ResultEnum.VERIFICATION_CODE_ERROR.getCode(),
                    ResultEnum.VERIFICATION_CODE_ERROR.getMessage());
        }
    }

    @RequestMapping("/register/view")
    public ModelAndView view(){
        return new ModelAndView("register/view");
    }

    @RequestMapping("/register/save")
    @ResponseBody
    public ResultVO save(@Valid RegisterForm form, BindingResult bindingResult) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        if (bindingResult.hasErrors()){
            return ResultVOUtils.error(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        if (!form.getPassword().equals(form.getReset_password())){
            return ResultVOUtils.error(ResultEnum.PASSWORD_NOT_SAME.getCode(),
                    ResultEnum.PASSWORD_NOT_SAME.getMessage());
        }
        if (userService.hasMore(form.getUserName())){
            return ResultVOUtils.error(ResultEnum.USERNAME_HAVE_MORE.getCode(),
                    ResultEnum.USERNAME_HAVE_MORE.getMessage());
        }
        User user=new User();
        form.setPassword(MD5SaltUtils.getEncryptedPwd(form.getPassword()));
        try {
            BeanUtils.copyProperties(form,user);
            userService.add(user);
        }catch (SellException e){
            return ResultVOUtils.error(ResultEnum.SAVE_ERROR.getCode(),
                    ResultEnum.SAVE_ERROR.getMessage());
        }
        return ResultVOUtils.success("注册成功");
    }

    @RequestMapping("/logout")
    @ResponseBody
    public ResultVO logout(HttpServletRequest request){
        Enumeration em = request.getSession().getAttributeNames();
        while(em.hasMoreElements()){
            request.getSession().removeAttribute(em.nextElement().toString());
        }
        return ResultVOUtils.success();
    }
}
